import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Address } from '../entities/address.entity';

@Injectable()
export class AddressService {
  constructor(
    @InjectRepository(Address)
    private addressRepository: Repository<Address>,
  ) {}

  async getAddress(phone: string): Promise<Address> {
    const address = await this.addressRepository.findOne({ where: { phone } });
    if (!address) {
      if (phone === '1') {
        return this.addressRepository.save({
          details: '',
          phone: '1',
          province: '',
          city: '',
          district: '',
        });
      }
      throw new NotFoundException(`未找到手机号为 ${phone} 的地址信息`);
    }
    return address;
  }

  async updateAddress(
    phone: string,
    addressData: Partial<Address>,
  ): Promise<Address> {
    let address = await this.addressRepository.findOne({ where: { phone } });
    if (!address) {
      address = this.addressRepository.create({
        phone,
        ...addressData,
      });
    } else {
      Object.assign(address, addressData);
    }
    return this.addressRepository.save(address);
  }
}
